package kingwing.dc.core.sevice.quartz.listener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import kingwing.dc.core.sevice.quartz.sevice.QuartzManager;

import org.quartz.Job;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class QuartzJobListener implements ServletContextListener {

	
	@SuppressWarnings("unchecked")
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		/***处理获取数据库的job表，然后遍历循环每个加到job中 ***/
        QuartzManager quartzManager = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()).getBean(QuartzManager.class);

        //此处就不写获取数据库了，模拟一个集合遍历的数据  
        List<Map<String,Object>> listMap=new ArrayList<>();
        Map<String, Object> map1=new HashMap<String, Object>();
        map1.put("jobClass","kingwing.dc.core.sevice.quartz.job.job");
        map1.put("jobName","检查任务表");
        map1.put("jobGroupName","检查任务表组名");
        map1.put("jobTime","0 */10 * * * ?");
        listMap.add(map1);

        for (Map<String, Object> map : listMap) {
            try {
                quartzManager.addJob((Class<? extends Job>)(Class.forName((String)map1.get("jobClass")).newInstance().getClass()),map.get("jobName").toString(), map.get("jobGroupName").toString(),map.get("jobTime").toString());
            } catch (Exception e) {
                e.printStackTrace();
            } 
        }
        System.out.println("任务扫描器启动啦&广西开云科技有限公司");

	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		/***处理获取数据库的job表，然后遍历循环每个加到job中 ***/
        QuartzManager quartzManager = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()).getBean(QuartzManager.class);

        try {
        	quartzManager.shutdownJobs();
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
        
	}

}
